﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Composite.Data;
using System.Transactions;
using Composite.Data.Transactions;
using LCA.Common.Extensions;
using LCA.Utils;
using LCA.Data;

public partial class Admin_LCASystem_Controls_SystemEditor : System.Web.UI.UserControl
{
    public Guid? SystemId
    {
        //get { return (Guid?)ViewState["SystemId"]; }
        //set
        //{
        //    ViewState["SystemId"] = value;
        //}
        get
        {
            return StringHelper.ParseGuid(Request.Params["systemId"]); 
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    public event EventHandler DataSaved;
    public event EventHandler Cancelled;

    protected virtual void OnDataSaved(EditorArgs e)
    {
        if (DataSaved != null)
        {
            DataSaved(this, e);
        }
    }

    protected virtual void OnCancelled(EventArgs e)
    {
        if (Cancelled != null)
        {
            Cancelled(this, e);
        }
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        OnCancelled(new EventArgs());
    }

    public void RefreshComponents()
    {
        using (DataConnection conn = new DataConnection())
        {
            // Bind Units
            var units = from u in conn.Get<LCA.Data.Unit>()
                        join uc in conn.Get<LCA.Data.UnitGroup>() on u.UnitGroup equals uc.Id
                        select new
                        {
                            Id = u.Id,
                            Name = uc.Name + " - " + u.Name
                        };
            units = units.OrderBy(x => x.Name);

            ddlUnit.DataSource = units;
            ddlUnit.DataBind();
            ddlUnit.Items.Insert(0, new ListItem("-- Please Select --", "NULL"));

            ctlInputOutput.RefreshComponents(SystemId);
            
            ctlTransportationA.RefreshComponents(SystemId);

            ctlTransportationB.RefreshComponents(SystemId);

            if (this.SystemId.HasValue)
            {
                LCA.Data.LCASystem system = conn.Get<LCA.Data.LCASystem>().Where(x => x.Id == this.SystemId.Value).FirstOrDefault();

                litItemHeader.Text = String.Format("Edit a system - {0} ({1})", system.Name, system.LCASystemId);
                txtName.Text = system.Name;
                rteDescription.Xhtml = system.Description;
                ddlUnit.SelectedValue = system.Unit.HasValue ? system.Unit.Value.ToString() : "NULL";
                imgSelectorPicture.SelectedImageId = string.IsNullOrEmpty(system.Picture) ? null : system.Picture.Replace("MediaArchive:", "").ToGuid();
                fileSelector.SelectedImageId = string.IsNullOrEmpty(system.Diagram) ? null : system.Diagram.Replace("MediaArchive:", "").ToGuid();
                txtAmount.Text = system.Amount.ToString();
            }
            else
            {
                litItemHeader.Text = "Create a system";
            }


        }


        
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Guid SystemId = SaveData();
            EditorArgs args = new EditorArgs();
            args.ItemId = SystemId;

            OnDataSaved(args);
        }
    }

    private Guid SaveData()
    {
        LCA.Data.LCASystem system = null;

        using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
        {
            using (DataConnection connection = new DataConnection())
            {
                if (this.SystemId.HasValue)
                {
                    system = connection.Get<LCA.Data.LCASystem>().Where(x => x.Id == this.SystemId.Value).FirstOrDefault();
                }
                else
                {
                    system = connection.CreateNew<LCA.Data.LCASystem>();
                    system.LCASystemId = Sequences.LCASystemId.NextVal.Value;
                    system.CreatedDate = DateTime.Now;
                }

                system.Name = txtName.Text.Trim();
                system.Description = rteDescription.Xhtml;
                system.Unit = ddlUnit.SelectedValue == "NULL" ? null : ddlUnit.SelectedValue.ToGuid();
                system.Amount = txtAmount.Text.Trim();
                system.Picture = imgSelectorPicture.SelectedImageId == null ? null : ("MediaArchive:" + imgSelectorPicture.SelectedImageId.ToString());
                system.Diagram = fileSelector.SelectedImageId == null ? null : ("MediaArchive:" + fileSelector.SelectedImageId.ToString());
                
                if (this.SystemId.HasValue)
                    connection.Update(system);
                else
                    connection.Add(system);


                // Save data for Input, Output
                ctlInputOutput.SaveData(system.Id);
                ctlTransportationA.SaveData(system.Id);
                ctlTransportationB.SaveData(system.Id);
            }
            transactionScope.Complete();
        }

        // this.SystemId = system.Id;

        return system.Id;
    }

}